import warnings
warnings.filterwarnings("ignore")

import os
from pathlib import Path
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt


def load_text(file_path: Path) -> str:
    if not file_path.exists():
        raise FileNotFoundError(f"未找到语料文件: {file_path}")
    return file_path.read_text(encoding='utf-8', errors='ignore')


def load_stopwords(file_path: Path) -> set:
    if not file_path.exists():
        return set()
    lines = file_path.read_text(encoding='utf-8', errors='ignore').splitlines()
    return set(w.strip() for w in lines if w.strip())


def segment(text: str, stopwords: set) -> str:
    tokens = (w.strip() for w in jieba.cut(text) if w.strip())
    filtered = [w for w in tokens if w not in stopwords and len(w) > 1]
    return " ".join(filtered)


def get_font_path() -> str:
    # 优先使用系统常见中文字体
    candidates = [
        r"C:\\Windows\\Fonts\\simhei.ttf",  # 黑体
        r"C:\\Windows\\Fonts\\simfang.ttf",  # 仿宋
        r"C:\\Windows\\Fonts\\msyh.ttc",   # 微软雅黑
    ]
    for p in candidates:
        if os.path.exists(p):
            return p
    # 兜底：不指定字体（可能出现方块字）
    return None


def main():
    project_root = Path(__file__).resolve().parent
    data_file = project_root / 'sample_text.txt'
    stop_file = project_root / 'stopwords.txt'
    out_dir = project_root / 'outputs'
    out_dir.mkdir(parents=True, exist_ok=True)
    out_path = out_dir / 'wordcloud.png'

    print("读取文本与停用词...")
    text = load_text(data_file)
    stopwords = load_stopwords(stop_file)

    print("进行中文分词与过滤...")
    segmented = segment(text, stopwords)

    font_path = get_font_path()
    if font_path is None:
        print("未找到中文字体，将尝试默认字体（可能出现乱码）。")

    print("生成词云...")
    wc = WordCloud(
        font_path=font_path,
        background_color='white',
        width=1200,
        height=800,
        max_words=300,
        collocations=False
    ).generate(segmented)

    wc.to_file(str(out_path))
    print(f"词云已保存: {out_path}")

    plt.figure(figsize=(10, 6))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis('off')
    plt.title('热点关键词云')
    plt.tight_layout()
    plt.show()


if __name__ == '__main__':
    main()


